package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        return lambdaQuery()
                .eq(StrUtil.isNotEmpty(dto.getFunctionId()),DeviceData::getFunctionId,dto.getFunctionId())//功能名称条件
                .eq(StrUtil.isNotEmpty(dto.getDeviceName()),DeviceData::getDeviceName,dto.getDeviceName())//设备名称条件
                .between(dto.getStartTime()!=null&&dto.getEndTime()!=null,DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime())//查询时间条件
                .list();
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }
    @Autowired
    private IDeviceService deviceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1.判断设备是否存在
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, iotMsgNotifyData.getHeader().getDeviceId())
                .one();
        if(device==null){
            return;
        }
        //2.将华为云传递过来的消息队列存储到数据库中
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        List<DeviceData> list =new ArrayList<>();
        for (IotMsgService service : services) {
            Map<String, Object> properties = service.getProperties();
            String eventTime = service.getEventTime();
            LocalDateTime activeTime= LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime beijingLocalDateTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            properties.forEach((k,v)->{
                //搬砖代码开始
                DeviceData deviceData= new DeviceData();
                deviceData.setDeviceName(device.getDeviceName());
                deviceData.setProductKey(device.getProductKey());
                deviceData.setProductName(device.getProductName());
                deviceData.setIotId(device.getIotId());
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setLocationType(device.getLocationType());
                deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
                deviceData.setDeviceDescription(device.getDeviceDescription());
                //搬砖代码结束
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(beijingLocalDateTime);
                list.add(deviceData);
            });
        }
        saveBatch(list);
        redisTemplate.opsForHash().put(Constants.IOT_DEVICE_LAST_DATA,device.getIotId(), JSONUtil.toJsonStr(list));
    }
}
